package org.wx.io.future;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @program: my-java
 * @description: Java Future 异步调用
 * @author: Wang.xun
 * @create: 2021-02-07 21:57
 **/
@Slf4j
public class TestFuture {
    public static void main(String[] args) {
        try {
            TestFuture TestFuture = new TestFuture();
            Future<UserInfo> future = TestFuture.queryUserInfo("1001");
            ExecutorService executorService = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 10; i++) { // 设置10个线程，去执行
                executorService.execute(()->{
                    UserInfo userInfo = null;
                    try {
                        userInfo = future.get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                    log.info(userInfo.toString());
                });
            }




        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 定义一个线程，去做一些耗时的任务
     * @param id
     * @return
     */
    private Future<UserInfo> queryUserInfo(String id) {
        FutureTask<UserInfo> task = new FutureTask<UserInfo>(() -> {
            Thread.sleep(30*1000);
            return new UserInfo(1001,31,"Jack");
        });

        new Thread(task).start();
        log.info("查询任务开始....");
        return task;
    }
}
